//
//  KZContentFile.m
//  xiaorizi
//
//  Created by kun on 15/10/31.
//  Copyright © 2015年 origin. All rights reserved.
//

#import "KZContentFile.h"
#import "MJExtension.h"
#import "EveryDayModel.h"


@interface KZContentFile ()

@property (nonatomic,copy) NSString *path;
@property (nonatomic,strong) NSMutableArray *dataM;

@end


@implementation KZContentFile

//1 实现全局唯一数据管理
+(KZContentFile *)shareInstance
{
    __strong static KZContentFile *contentFile = nil;
    
    if(!contentFile)
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            contentFile = [[KZContentFile alloc]init];
        });
    }
    
    return contentFile;
}

//从写init方法

-(KZContentFile *)init
{
    if(self = [super init])
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        //收藏实现plist文件存储地址
        self.path = [paths[0] stringByAppendingPathComponent:@"collectData.plist"];
        
        //数据转存
        [self load];
    }
    return self;
}

- (void)load
{
    //获取路径
    [EveryDayModel setupIgnoredCodingPropertyNames:^NSArray *{
        return @[@"themes",@"cellHeight"];
    }];
    
    NSString *filePath = self.path;
    
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    //初始化数据进行解档
    self.dataM = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    
    if(!data)
    {
        self.dataM = [NSMutableArray array];
    }
}


//2 添加元素对数据进行 归档  这里往数据改变元素加锁
-(void)addContentData:(EveryDayModel *)data
{
    //数据中添加 对象 然后 归档
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self.dataM addObject:data];
        //2归档
        NSData *datafile = [NSKeyedArchiver archivedDataWithRootObject: self.dataM];
        
        //文档写入
        [datafile writeToFile:self.path atomically:YES];

    });
    
}


//3 删除对象
-(void)removeContentData:(EveryDayModel *)data
{
    //先解档案
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self.dataM removeObject:data];
        //从新归档
        NSData *datafile = [NSKeyedArchiver archivedDataWithRootObject:self.dataM];
        [datafile writeToFile:self.path atomically:YES];

    });
    
}


//返回数据个数
-(NSUInteger)contentDataCount
{
    return self.dataM.count;
}


//返回制定索引的数据
- (id ) contentDataAtIndex: (NSUInteger) index
{
    return self.dataM[index];
}





@end
